import { constantRoutes } from '@/router'
import Layout from '@/layout'
import { treeList } from '@/api/system/menu'

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRoutes = asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
        route.path = `/${route.path}`
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  // 404 page must be placed at the end !!!
  // { path: "*", redirect: "/404", hidden: true }
  accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })

  return accessedRoutes
}

// 加载路由组件资源
export const loadView = view => {
  // return () => import(`@/views/${view}`);
  return resolve => require([`@/views/${view}`], resolve)
}

const state = {
  routes: [],
  accessedRoutes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    state.accessedRoutes = routes
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      // var data = [
      //   {
      //     path: "/system",
      //     component: "Layout",
      //     name: "system",
      //     meta: { title: "系统管理", icon: "el-icon-setting" },
      //     children: [
      //       {
      //         path: "menu",
      //         name: "menu",
      //         component: "system/menu/index",
      //         meta: { title: "菜单管理", icon: "table" },
      //       },
      //       {
      //         path: "job",
      //         name: "job",
      //         component: "system/job/index",
      //         meta: { title: "任务调度管理", icon: "tree" },
      //       },
      //     ],
      //   },
      // ];
      // let accessedRoutes = filterAsyncRouter(data);
      // commit("SET_ROUTES", accessedRoutes);
      // resolve(accessedRoutes);
      const params = {}
      treeList(params).then(data => {
          const accessedRoutes = filterAsyncRouter(data)
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }).catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
